package com.yykj.weifenxiao.server.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.yykj.common.util.HttpUtil;
import com.yykj.drup.client.WiFenXiaoOrder;
import com.yykj.drup.client.form.WiFenXiaoPayOrderFrom;
import com.yykj.weifenxiao.server.config.WiFenXiaoConfig;
import com.yykj.weifenxiao.server.service.AccessTokenService;
import com.yykj.weifenxiao.server.service.WiFenXiaoOrderService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author zeng
 * @Date 2022/4/1
 */
@Service
@AllArgsConstructor
@Slf4j
public class WiFenXiaoOrderServiceImpl implements WiFenXiaoOrderService {

    final AccessTokenService accessTokenService;


    @Override
    public WiFenXiaoOrder wiFenXiaopayOrder(WiFenXiaoPayOrderFrom wiFenXiaoFrom) {
        wiFenXiaoFrom.setAccess_token(accessTokenService.getAccessToken());
        String result = HttpRequest.post(WiFenXiaoConfig.baseUrl + "/order/create")
                //头信息，多个头信息多次调用此方法即可
                .header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded")
                //表单内容
                .form(BeanUtil.beanToMap(wiFenXiaoFrom))
                //超时，毫秒
                .timeout(20000)
                .execute().body();
        log.info("微分销下单返回数据：{}",result);
        WiFenXiaoOrder fenXiaoOrder = JSONUtil.toBean(result, WiFenXiaoOrder.class);
        log.info("WiFenXiaoOrder：{}",fenXiaoOrder);
        return fenXiaoOrder;


    }

    @Override
    public WiFenXiaoOrder wiFenXiaoFindOrder(String orgOrderNu) {
        String accessToken = accessTokenService.getAccessToken();
        String requestUrl = "/order/info";
        Map<String,Object> map = new HashMap<>();
        map.put("access_token",accessToken);
        map.put("order_no",orgOrderNu);
        try {
            String body = HttpUtil.get(WiFenXiaoConfig.baseUrl + requestUrl, map);
            System.out.println(body);
            JSONObject jsonObject = JSONUtil.parseObj(body);
            WiFenXiaoOrder wiFenXiaoOrder = JSONUtil.toBean(jsonObject,WiFenXiaoOrder.class);
            return wiFenXiaoOrder;
        } catch (UnirestException e) {
            e.printStackTrace();
        }
        return null;
    }
}
